<template>
    <div>
        <div class="e-form">
            <BillTop @cancel="handleClose"></BillTop>
            <div class="tabs" style="margin-bottom:120px">
                <div class="tabs-title">基本信息</div>
                <div style="width: 100%" class="form">
                    <el-form
                        :model="formData"
                        :label-width="formLabelWidth"
                        :rules="rulesBase"
                        ref="rulesBase"
                        class="demo-ruleForm"
                    >
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="合同名称：" prop="contractId">
                                    <el-input
                                        v-model="formData.contractName"
                                        autocomplete="off"
                                        readonly
                                    >
                                        <i
                                            class="
                                                el-icon-document-copy
                                            "
                                            slot="suffix"
                                                @click="selectContract"
                                        >
                                        </i>
                                    </el-input>
                                    <el-button class="btn-blue" style="margin-left:5px" @click="showContract">查看</el-button>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="外包方：">
                                    <span>{{ formData.outsourcerName }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="结算日期：" prop="settlementDate">
                                    <el-date-picker
                                        type="date"
                                        value-format="yyyy-MM-dd"
                                        placeholder="选择日期"
                                        v-model="formData.settlementDate
                                        "
                                        style="width: 100%"
                                    ></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="币种：">
                                    <span>{{ formData.currency }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="状态：">
                                    <span>{{ state.find(x=>x.value === parseInt(formData.state) ).label  }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="录入机构：">
                                    <span>{{
                                        userInfo.orgInfo.orgName
                                    }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="人民币汇率：">
                                    <span>{{
                                        formData.rmbRate
                                    }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="传输财务共享：">
                                    <span>{{ formData.easId ? "已传" : '未传' }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="本位币：">
                                    <span>{{
                                        formData.baseCurName
                                    }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                    <el-form-item label="本位币汇率：" prop="baseCurRate">
                                        <el-input
                                            v-model="formData.baseCurRate"

                                            v-enter-float2="{
                                                set: this,
                                                val:'formData',
                                                key: 'baseCurRate'
                                            }"
                                            placeholder="请输入内容"
                                            :disabled="!showBaseCurName">
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                        </el-row>
                    </el-form>
                </div>
            </div>
            <div class="buttons">
                <el-button type="primary" size="small" style="background: #2e61d7" @click="addSave"
                    >保存</el-button
                >
                <el-button size="small" @click="handleClose">取消</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { createBond, listPreviousTotalReturnDepositInfo, updateBondList } from '@/api/settlementManagement/gongchengjieshuan/baozhengjin.js'
import { showLoading, hideLoading, formatDate, openAppClient, selectDataClient } from '@/utils/common'
import { baseCurRate } from '@/utils/rules.js'
export default {
    data () {
        return {
            //基础信息
            formData: {
                'amount': 0,
                'baseCurAmount': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'billNo': '',
                'contractId': '',
                'contractName': '',
                'currency': '',
                'currencyId': '',
                'easId': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'outsourcerId': '',
                'outsourcerName': '',
                'period': 0,
                'remarks': '',
                'rmbAmount': 0,
                'rmbId': '',
                'rmbName': '',
                'rmbRate': 0,
                'settlementDate': '',
                'state': 0,
                'workId': ''
            },
            formLabelWidth: '200px',
            billid: '',
            rulesBase: {
                settlementDate: [
                    { required: true, message: '请选择结算日期', trigger: 'change' },
                ],
                contractId: [
                    { required: true, message: '请选择合同', trigger: 'change' },
                ],
                baseCurRate: [
                    { required: true, validator: baseCurRate, trigger: 'change' },
                ],
            },
            settlementList: [], //结算列表
            bonds: null,
            showBaseCurName: true
        }
    },
    mounted () {
        this.formData.settlementDate = formatDate(new Date(), 'yyyy-MM-dd')
    },
    components: {
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            state: state => state.equip.equipData.state, //通用流程状态
        })
    },
    methods: {
        //新增基本信息
        addSave () {
            this.$refs.rulesBase.validate(valid => {
                if (valid) {
                    showLoading()
                    createBond(this.formData).then(res=>{
                        this.billid = res
                        this.saveSettlementList()
                        hideLoading()
                        this.clientPop('info', '保存成功，是否继续？', ()=>{
                            this.$router.replace({
                                path: '/baozhengjinEdit',
                                query: {
                                    billid: res,
                                    name: 'mainInfo'
                                }
                            })
                        }, this.handleClose)
                    })
                }
            })
        },
        //取消
        handleClose () {
            hideLoading()
            this.$router.replace('/baozhengjinList')
        },
        showContract () {
            if(!this.formData.contractId) return
            openAppClient(`/contractDefinitionShow?billid=${this.formData.contractId}&isview=true`, '查看分包合同')
        },
        //选择合同
        selectContract () {
            const ids = this.formData.contractId ? [this.formData.contractId] : []
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/subcontract/thirdParty/getReturnBondSettlement', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择合同', // 标题
            }).then(val => {
                this.clearList()
                this.formData.contractName = val[0].contractName
                this.formData.contractId = val[0].contractId
                this.formData.currency = val[0].currencyName
                this.formData.currencyId = val[0].currencyId
                this.formData.baseCurName = val[0].baseCurName
                this.formData.baseCurId = val[0].baseCurId
                this.formData.baseCurRate = val[0].baseCurId === val[0].currencyId ? 1 : val[0].baseCurRate
                this.showBaseCurName = val[0].baseCurId === val[0].currencyId ? false : true
                this.formData.rmbRate = val[0].rmbRate
                this.formData.outsourcerName = val[0].secondPartyName
                this.formData.outsourcerId = val[0].secondPartyId
                this.bonds = val[0].bonds
            })
        },
        saveSettlementList () {
            listPreviousTotalReturnDepositInfo({
                contractId: this.formData.contractId,
                orgId: this.formData.orgId,
            }).then(res=>{
                this.bonds.forEach(item=>{
                    const depositInfo1 = res.find(x=>x.itemId === item.billId && x.marginType === 1) //扣类
                    const depositInfo2 = res.find(x=>x.itemId === item.billId && x.marginType === 2) //返类
                    const obj1 = { //扣类
                        'billId': this.billid,
                        'changeType': 1,
                        'contractAmount': item.deductionAmount,
                        'contractProportion': item.deductionRatio,
                        'currentTotalAmount': 0,
                        'currentTotalProportion': 0,
                        'dtlId': '',
                        'itemId': item.billId,
                        'itemName': item.name,
                        'itemNo': '扣',
                        'marginType': 1,
                        'previousTotalAmount': depositInfo1 ? depositInfo1.previousTotalAmount : 0,
                        'previousTotalProportion': depositInfo1 ? depositInfo1.previousTotalProportion : 0,
                        'settlementAmount': 0,
                        'settlementProportion': 0
                    }

                    this.settlementList.push(obj1)
                    const obj2 = { //返类
                        'billId': this.billid,
                        'changeType': 1,
                        'contractAmount': item.deductionAmount,
                        'contractProportion': item.deductionRatio,
                        'currentTotalAmount': 0,
                        'currentTotalProportion': 0,
                        'dtlId': '',
                        'itemId': item.billId,
                        'itemName': item.name,
                        'itemNo': '返',
                        'marginType': 2,
                        'previousTotalAmount': depositInfo2 ? depositInfo2.previousTotalAmount : 0,
                        'previousTotalProportion': depositInfo2 ? depositInfo2.previousTotalProportion : 0,
                        'settlementAmount': 0,
                        'settlementProportion': 0
                    }

                    this.settlementList.push(obj2)
                })
                this.summaryAmount()
                updateBondList(this.settlementList).then()
            })
        },
        //清空清单
        clearList () {
            for(let i = 0;i < this.settlementList.length;i++) {
                if( this.settlementList[i].changeType === 1 ) {
                    this.settlementList.splice(i, 1)
                    i--
                }else{
                    this.settlementList[i].changeType = -1
                }
            }
        },
        //修改金额
        changeAmount (row, index) {
            this.tableIndex = index
            row.changeType = row.changeType !== -1 && row.changeType !== 1 ? 2 : 1
            row.settlementProportion =  (parseInt(row.settlementAmount ? row.settlementAmount : 0) * 100 / parseFloat(row.contractAmount)).toFixed(2)
            row.currentTotalAmount = parseFloat(row.settlementAmount ? row.settlementAmount : 0)  +  parseFloat(row.previousTotalAmount)
            row.currentTotalProportion = (parseInt(row.currentTotalAmount ? row.currentTotalAmount : 0) * 100 / parseFloat(row.contractAmount)).toFixed(2)
            this.summaryAmount()
        },
        //汇总金额
        summaryAmount () {
            this.formData.amount = this.settlementList.reduce(((prev, item)=>{
                return prev + (item.changeType !== -1 ? parseInt(item.settlementAmount)  : 0)
            }), 0)
        },
    },
}

</script>

<style lang='scss' scoped>
.buttons {
    left: 0;
}
.e-form {
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}
.e-table{
    min-height: auto;
    background: #fff;
}
.separ{
   width: 30px;
   height: 40px;
   line-height: 18px;
   text-align: center;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}
</style>